package com.xiaotu.spider.maoyan.pageprocessor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.xiaotu.common.model.MaoYanMovieBasicInfoModel;
import com.xiaotu.common.model.StarTvWorksModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.PageUtils;
import com.xiaotu.common.util.UUIDUtils;
import com.xiaotu.server.service.maoyan.MaoYanMovieBasicInfoService;
import com.xiaotu.spider.AUrlPageProcessor;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Html;
@Component("MaoYanStarWorksSupplementPageProcessor")
public class MaoYanStarWorksSupplementPageProcessor extends AUrlPageProcessor {
	
    @Autowired
    private MaoYanMovieBasicInfoService maoYanMovieBasicInfoService;
    
	@Override
	public void process(Page page) {
		
		Map<String, Object> extrasMap = page.getRequest().getExtras();
		
		switch (this.getPageDataType(page))
        {
            case "/celebritylist":
            	this.basicinfoPeoplelistProcess(page,extrasMap);
            	break;
            default:this.addRequestProcess(page);
        }
		
	}

	//人员相关
	@SuppressWarnings("unchecked")
	protected void basicinfoPeoplelistProcess(Page page, Map<String, Object> extrasMap) {
		String url = page.getRequest().getUrl();
		String dataid = extrasMap.get("dataid").toString();
		String tvname = extrasMap.get("tvname").toString();
		if(url.contains(dataid)){
			
			//存放艺人与作品
			List<StarTvWorksModel> starTvWorksModelList = new ArrayList<StarTvWorksModel>();
			
			MaoYanMovieBasicInfoModel maoYanMovieBasicInfoModel = new MaoYanMovieBasicInfoModel();

			maoYanMovieBasicInfoModel.setTvname(tvname);
			maoYanMovieBasicInfoModel.setDataid(dataid);
			
			List<String> dlTagAll = page.getHtml().xpath("//div[@class='sticky-container']//div[@class='scroller cat-wrapper']//div[@class='wrapper cat-content']"
					+ "//div[@class='panel-wrapper']//dl").all();
			for(String dl : dlTagAll){
				//获取所有人员
				Map<String,Object> resultAll = convertPeopleRelateInfo(new Html(dl),true,maoYanMovieBasicInfoModel,starTvWorksModelList);
				starTvWorksModelList = (List<StarTvWorksModel>)resultAll.get("starTvWorksModelList"); 
			}
			//保存
			page.putField(StarTvWorksModel.class.getName(), starTvWorksModelList);
		}
	}
	
	
	private Map<String,Object> convertPeopleRelateInfo(Html dlHtml,boolean isAll,MaoYanMovieBasicInfoModel maoYanMovieBasicInfoModel,List<StarTvWorksModel> starTvWorksModelList){
		
		Map<String,Object> result = new HashMap<String,Object>();
		
		String occupation = dlHtml.xpath("//dl[@class='panel-main category']//dt[@class='panel-header sticky-wrapper']//span[@class='title-name']//text()").get();
		
		List<String> contentAll = dlHtml.xpath("//dl[@class='panel-main category']//dd[@class='panel-content']//div[@class='p-item']").all();
		String[][] nameAndEngNameAndRole = new String[3][];
		int size = 0;
		if(!isAll){
			size = contentAll.size()<=10?contentAll.size():10;
		}else{
			size = contentAll.size();
		}
		String [] nameArr = new String[size]; 
		String [] engNameArr = new String[size];
		String [] roleArr = new String[size];
//		if(occupation.equals("导演") || occupation.equals("演员") || occupation.equals("编剧")
//				|| occupation.equals("制片人") || occupation.equals("摄影师")
//				|| occupation.equals("出品人") || occupation.equals("发行")){
		int ordertype = 1;
		for(int i=0;i<size;i++){
			
			
			String starId = new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']/@data-id").get();
			
			String name = new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
					+ "//p[@class='p-item-name ellipsis-1']//text()").get()==null?"":new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
							+ "//p[@class='p-item-name ellipsis-1']//text()").get();
			String engName = new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
					+ "//p[@class='p-item-e-name ellipsis-1']//text()").get()==null?"":new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
							+ "//p[@class='p-item-e-name ellipsis-1']//text()").get();
			String role = new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
					+ "//p[@class='p-item-play ellipsis-1']//text()").get()==null?"":new Html(contentAll.get(i)).xpath("//div[@class='p-item']//a[@class='p-link']//div[@class='p-desc']"
							+ "//p[@class='p-item-play ellipsis-1']//text()").get().replace("饰：", "").replace("（配音）", "");
			nameArr[i] = name.replaceAll("[\"]", "").replace(",", "/");
			engNameArr[i] = engName.replaceAll("[\"]", "").replace(",", "/");
			roleArr[i] = role.replaceAll("[\"]", "").replace(",", "/");
			if(isAll){
				starTvWorksModelList.add(new StarTvWorksModel(
						UUIDUtils.getId(),null,null,
						maoYanMovieBasicInfoModel.getDataid(),
						maoYanMovieBasicInfoModel.getTvname(),
						starId, name, role,
						occupation,Constants.SiteName.MAOYAN,
						ordertype++,
						System.currentTimeMillis()
						));
			}
		}
		for(int j=0;j<nameArr.length;j++){
			if(StringUtils.isNotEmpty(nameArr[j])){
				nameAndEngNameAndRole[0] = nameArr;
			}
			if(StringUtils.isNotEmpty(engNameArr[j])){
				nameAndEngNameAndRole[1] = engNameArr;
			}
			if(StringUtils.isNotEmpty(roleArr[j])){
				nameAndEngNameAndRole[2] = roleArr;
			}
		}
			
		//}
		result.put("nameAndEngNameAndRole", nameAndEngNameAndRole);
		result.put("flag", occupation);
		if(null != starTvWorksModelList && isAll){
			result.put("starTvWorksModelList", starTvWorksModelList);
		}
		return result;
	}
	
	public void addRequestProcess(Page page){
		List<MaoYanMovieBasicInfoModel> list = new ArrayList<MaoYanMovieBasicInfoModel>();
		for(MaoYanMovieBasicInfoModel obj : list) {
			Map<String,Object> extraMap = new HashMap<String,Object>();
			extraMap.put("dataid", obj.getDataid());
			extraMap.put("tvname", obj.getTvname());
			PageUtils.addTargetRequest(page, String.format("http://piaofang.maoyan.com/movie/%s/celebritylist", obj.getDataid()), extraMap);
		}
		
	}
	
	
	@Override
	protected String[] getStartRequestUrls() {
		return new String[]{"http://piaofang.maoyan.com/dashboard"};
	}
	
	@Override
	protected String getSpiderType() {
		return Constants.SpiderTaskType.MOVIE_BOXOFFICE;
	}

	@Override
	public String getPageDataType(Page page) {
		String url = page.getUrl().toString();
        if (url.contains("/celebritylist")){
			return "/celebritylist";
		}
        return Constants.PageDataType.SEARCH_LIST;
	}

	
	
	protected String convertDateStr(String str){
    	String first = str.substring(0,4);
    	String second = str.substring(4, 6);
    	String three = str.substring(6);
    	return first+"-"+second+"-"+three;
    }
	
	
}
